<script setup lang="ts">
import {
  getProjectList,
  getEmailConfig,
  saveEmailConfig,
  getYamlConfig,
  getYamlRuntime,
  getYamlExecution,
  saveYamlConfig,
  overallUpdateYamlConfig,
  getCreater,
  getActiveMachines,
  bindSlaveIP,
  getBindSlaveIp
} from "@/api/file";
import yamlLabel from "./yamlLabel.json";
import { ref, onMounted, nextTick, reactive, computed } from "vue";
import { onBeforeRouteLeave } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import type { Action, FormRules } from 'element-plus'
import YamlTable from "./yamlConfig.vue";
import FormItem from "./formItem.vue";
import FormItemSimple from "./formItemSimple.vue";
import Question from "@iconify-icons/ep/question-filled";
import emailConfigLabel from "./emailConfigLabel.json";
import { storageSession } from "@pureadmin/utils";

defineOptions({
  name: "project"
});
type userType = {
  username?: string;
  roles?: Array<string>;
};
const userInfo: userType = storageSession().getItem("user-info");
const projectList = ref([]);
const orginProjectName = ref("");
const projectName = ref("");
const activeName = ref("yaml");
const loading = ref(false);
const reflesh = ref(true);
const emailConfig = ref(null);
const yamlConfig = ref({
  runtime: 0,
  execution: [],
});
const pagination = ref({
  total: 0,
  pageNum: 1,
  pageSize: 10,
})
const formChanged = ref(false);
const dialogVisible = ref(false);
const dialogForm = reactive({
  "concurrency": 1,
  "targettime": 1,
  "ramp-up": 1
});
const createrName = ref("");
const bindSlaveIPString = ref("");
const searchScenario = ref("");
const dialogBindVisible = ref(false);
const slaveIpOptions = ref([]);
const dialogBindLoading = ref(false);
const form = ref({
  projectName: "",
  bindSlaverIp: []
});
const rules = reactive<FormRules>({
  projectName: [{ required: true, message: "请选择项目", trigger: "blur" }],
  bindSlaverIp: [{ required: true, message: "绑定测试机", trigger: "blur" }]

});
const dialogBindForm = ref({
  bindSlaverIp: []
});
const selectLoading = ref(false);
// const bindSlaveIPString = computed(() => {
//   return form.value.bindSlaverIp.join(",");
// });
// 页面渲染完毕时执行
onMounted(async () => {
  await getList();
  let session = sessionStorage.getItem('projectName')
  if (projectList.value.includes(session)) {
    projectName.value = session
    getYaml();
    getCreaterInfo();
    getBindIp();
  }
  // if (projectList.value.length != 0) {
  //   projectName.value = projectList.value[0];
  // }
});

// 在页面离开前触发
onBeforeRouteLeave((to, from, next) => {
  if (formChanged.value) {
    ElMessageBox.confirm("表单内容已更改，确定要离开吗？", "警告", {
      confirmButtonText: "离开",
      cancelButtonText: "保存并离开",
      distinguishCancelAndClose: true,
      type: "warning"
    })
      .then(() => {
        next();
      })
      .catch((action: Action) => {
        if (action === 'cancel') {
          if (activeName.value == "email") {
            saveEmail().then(() => { next(); });
          } else if (activeName.value == "yaml") {
            saveYaml().then(() => { next(); });
          }
        } else {
          next(false); // 取消页面切换
        }
      });
  } else {
    next();
  }
});

const getBindIp = async () => {
  try {
    const res = await getBindSlaveIp({ projectName: projectName.value });
    if (res.success) {
      bindSlaveIPString.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error(error);
  }
};

const getCreaterInfo = async () => {
  try {
    const res = await getCreater({ projectName: projectName.value });
    if (res.success) {
      createrName.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error(error);
  }
};

const handleChange = (value: string) => {
  if (formChanged.value) {
    return ElMessageBox.confirm("表单内容已更改，确定要离开吗？", "警告", {
      confirmButtonText: "离开",
      cancelButtonText: "保存并离开",
      distinguishCancelAndClose: true,
      type: "warning"
    })
      .then(() => {
        searchScenario.value = ''
        sessionStorage.setItem('projectName', value)
        orginProjectName.value = value;
        getCreaterInfo();
        getBindIp();
        if (activeName.value == "email") {
          getEmail();
        } else if (activeName.value == "yaml") {
          getYaml();
        }
      })
      .catch((action: Action) => {
        if (action === 'cancel') {
          if (activeName.value == "email") {
            saveEmail(orginProjectName.value).then(() => { getEmail();; });
          } else if (activeName.value == "yaml") {
            saveYaml(orginProjectName.value).then(() => { getYaml(); });
          }
          sessionStorage.setItem('projectName', value)
          orginProjectName.value = value;
        } else {
          projectName.value = orginProjectName.value; // 取消页面切换
        }
      });
  } else {
    searchScenario.value = ''
    sessionStorage.setItem('projectName', value)
    orginProjectName.value = value;
    getCreaterInfo();
    getBindIp();
    if (activeName.value == "email") {
      getEmail();
    } else if (activeName.value == "yaml") {
      getYaml();
    }
  }
};

const dialogConfirm = async () => {
  try {
    dialogVisible.value = false
    const res = await overallUpdateYamlConfig({
      projectName: projectName.value,
      data: dialogForm
    });
    if (res.success) {
      formChanged.value = false;
      ElMessage.success("修改成功");
      getYaml();
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error(error);
  }
}

// yaml和邮箱tab被点击时执行
const tabChange = (pane: string) => {
  if (pane == "email") {
    getEmail();
  } else if (pane == "yaml") {
    getYaml();
  }
};

const beforeTabLeave = () => {
  if (formChanged.value) {
    return ElMessageBox.confirm("表单内容已更改，确定要离开吗？", "警告", {
      confirmButtonText: "离开",
      cancelButtonText: "保存并离开",
      distinguishCancelAndClose: true,
      type: "warning"
    })
      .then(() => {
        return true;
      })
      .catch((action: Action) => {
        if (action === 'cancel') {
          if (activeName.value == "email") {
            saveEmail().then(() => true);
          } else if (activeName.value == "yaml") {
            saveYaml().then(() => true);
          }
        } else {
          return false; // 取消页面切换
        }
      });
  } else {
    return true;
  }
};

// 获取项目列表
const getList = async () => {
  try {
    const res = await getProjectList();
    if (res.success) {
      projectList.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error(error);
  }
};

// 获取邮件配置
const getEmail = async () => {
  try {
    loading.value = true;
    const res = await getEmailConfig({ projectName: projectName.value });
    loading.value = false;
    if (res.success) {
      // ElMessage.success("获取成功");
      emailConfig.value = res.data;
      formChanged.value = false;
    } else {
      ElMessage.error(res.msg);
      emailConfig.value = null;
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

// 保存邮件配置
const saveEmail = async (project?: string) => {
  try {
    const params = {
      projectName: project || projectName.value,
      data: emailConfig.value
    };
    loading.value = true;
    const res = await saveEmailConfig(params);
    loading.value = false;
    if (res.success) {
      formChanged.value = false;
      ElMessage.success("修改成功");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

// 获取yaml配置
const getYaml = async () => {
  try {
    loading.value = true;
    // const res = await getYamlConfig({ projectName: projectName.value });
    const res = await Promise.all([getYamlRuntime({ projectName: projectName.value }), getYamlExecution({ projectName: projectName.value, sencrioName: searchScenario.value, pageNum: pagination.value.pageNum, pageSize: pagination.value.pageSize })]);
    loading.value = false;
    if (res[0].success) {
      yamlConfig.value.runtime = res[0].data.runtime;
    } else {
      ElMessage.error(res[0].msg);
      yamlConfig.value.runtime = null;
    }
    if (res[1].success) {
      yamlConfig.value.execution = res[1].data.list
      pagination.value.total = res[1].data.total
    } else {
      ElMessage.error(res[1].msg);
      yamlConfig.value.execution = [];
      pagination.value.total = 0
    }
  } catch (err) {
    loading.value = false;
    ElMessage.error(err);
  }
};

const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  getYaml()
}
const handleCurrentChange = (val: number) => {
  pagination.value.pageNum = val
  getYaml()
}

// 保存yaml配置
const saveYaml = async (project?: string) => {
  try {
    const params = {
      projectName: project || projectName.value,
      data: yamlConfig.value
    };
    loading.value = true;
    const res = await saveYamlConfig(params);
    loading.value = false;
    if (res.success) {
      formChanged.value = false;
      ElMessage.success("保存成功");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (err) {
    loading.value = false;
    ElMessage.error(err.msg);
  }
};

const handleVisibleBindChange = async (visible: boolean) => {
  if (visible) {
    try {
      selectLoading.value = true;
      const res = await getActiveMachines({ projectName: projectName.value });
      selectLoading.value = false;
      if (res.success) {
        slaveIpOptions.value = res.data;
        ElMessage.success(res.msg);
      } else {
        ElMessage.error(res.msg);
      }
    } catch (error) {
      selectLoading.value = false;
      ElMessage.error(error);
    }
  }
};

const handleUpdateBindValue = async () => {
  try {
    dialogBindLoading.value = true;
    const res = await bindSlaveIP({
      projectName: projectName.value,
      slaverIp: dialogBindForm.value.bindSlaverIp
    });
    // ElMessage.success(JSON.stringify(dialogBindForm.value))
    dialogBindLoading.value = false;
    if (res.success) {
      form.value.bindSlaverIp = res.data;
      ElMessage.success(res.msg);
      dialogBindVisible.value = false;
      getBindIp();
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    dialogBindLoading.value = false;
    ElMessage.error(error);
  }
};

// yaml配置修改
// const changeData = (key: string, value: any) => {
//   formChanged.value = true;
//   console.log("顶层changedata触发");
//   yamlConfig.value[key] = value;
// };
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>项目配置</span>
      </div>
    </template>
    <div v-loading="loading">
      <div class="flex items-center justify-between">
        <div class="flex  items-center ">
          <el-form ref="ruleFormRef" :model="form" :rules="rules" inline>
            <el-select filterable v-model="projectName" placeholder="请选择项目" @change="handleChange">
              <el-option v-for="item in projectList" :key="item" :label="item" :value="item" />
            </el-select>
            <el-form-item label="分配测试机" class="create-item"
              v-if="projectName && userInfo.roles && userInfo.roles.includes('admin')">
              <el-input v-model="bindSlaveIPString" placeholder="分配测试机" readonly @click="dialogBindVisible = true" />
            </el-form-item>
            <el-form-item label="创建人" class="create-item"><el-input v-model="createrName" clearable disabled />
            </el-form-item>
          </el-form>
        </div>
        <el-button v-if="yamlConfig && activeName === 'yaml'" type="primary"
          @click="dialogVisible = true">快速修改</el-button>
        <el-dialog v-model="dialogVisible" title="全局策略速配">
          <el-form :model="dialogForm" label-width="auto">
            <el-form-item :label="yamlLabel['concurrency']">
              <el-input-number v-model="dialogForm.concurrency" :value-on-clear="0" :min="0" />
            </el-form-item>
            <el-form-item :label="yamlLabel['ramp-up']">
              <el-input-number v-model="dialogForm['ramp-up']" :value-on-clear="0" :min="0" />&nbsp s
            </el-form-item>
            <el-form-item :label="yamlLabel['targettime']">
              <el-input-number v-model="dialogForm.targettime" :value-on-clear="0" :min="0" />&nbsp ms
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="dialogConfirm">
                确定
              </el-button>
            </div>
          </template>
        </el-dialog>
        <el-dialog v-model="dialogBindVisible" title="绑定测试机" width="500">
          <el-form :model="dialogBindForm">
            <el-form-item label="绑定测试机">
              <el-select v-model="dialogBindForm.bindSlaverIp" placeholder="请选择" :loading="selectLoading" multiple
                @visible-change="handleVisibleBindChange">
                <el-option v-for="item in slaveIpOptions" :key="item.ip" :label="item.ip" :value="item.ip" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogBindVisible = false" :loading="dialogBindLoading">取消</el-button>
              <el-button type="primary" :loading="dialogBindLoading" @click="handleUpdateBindValue">
                确定
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <el-tabs v-if="projectName" v-model="activeName" class="demo-tabs" type="border-card" @tab-change="tabChange"
        :before-leave="beforeTabLeave">
        <el-tab-pane label="测试策略" name="yaml" lazy>
          <el-space style="margin-bottom: 10px;">
            <el-input v-model="searchScenario" clearable placeholder="请输入场景名" style="width: 200px;" />
            <el-button type="primary" @click="getYaml">搜索</el-button>
          </el-space>
          <YamlTable :projectName="projectName" :yamlConfig="yamlConfig" :pagination="pagination" @getYaml="getYaml"
            @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
          </YamlTable>
          <!-- <el-form v-if="yamlConfig" ref="formRef" :model="yamlConfig">
            <template v-if="reflesh">
              <FormItemSimple label="settings" :data="yamlConfig.settings" @data-change="changeData" />
              <FormItem label="execution" :data="yamlConfig.execution" :projectName="projectName"
                @data-change="changeData" />
            </template>
            <div class="form-footer">
              <el-form-item>
                <el-button @click="getYaml()">重置</el-button>
                <el-button type="primary" @click="saveYaml()">保存</el-button>
              </el-form-item>
            </div>
          </el-form> -->
        </el-tab-pane>
        <el-tab-pane label="邮件配置" name="email" lazy>
          <el-form v-if="emailConfig" ref="formRef" :model="emailConfig" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>项目信息</span>
                    </div>
                  </template>
                  <el-form-item :label="emailConfigLabel['projectname']" :prop="(['TestInfo', 'projectname'] as any[])">
                    <el-input v-model="emailConfig['TestInfo']['projectname']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['version']" :prop="(['TestInfo', 'version'] as any[])">
                    <el-input v-model="emailConfig['TestInfo']['version']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['weburl']" :prop="(['TestInfo', 'weburl'] as any[])">
                    <el-input v-model="emailConfig['TestInfo']['weburl']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['db']" :prop="(['TestInfo', 'db'] as any[])">
                    <el-input v-model="emailConfig['TestInfo']['db']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                  <!-- <el-form-item :label="emailConfigLabel['fullreport']" :prop="(['TestInfo', 'fullreport'] as any[])">
                    <el-input v-model="emailConfig['TestInfo']['fullreport']" @input="formChanged = true">
                    </el-input>
                  </el-form-item> -->
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>邮件信息</span>
                    </div>
                  </template>
                  <el-form-item :label="emailConfigLabel['from_name']" :prop="(['EmailInfo', 'from_name'] as any[])">
                    <el-input v-model="emailConfig['EmailInfo']['from_name']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['from_addr']" :prop="(['EmailInfo', 'from_addr'] as any[])">
                    <el-input v-model="emailConfig['EmailInfo']['from_addr']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['password']" :prop="(['EmailInfo', 'password'] as any[])">
                    <el-input type="password" v-model="emailConfig['EmailInfo']['password']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['to_addr']" :prop="(['EmailInfo', 'to_addr'] as any[])">
                    <el-input v-model="emailConfig['EmailInfo']['to_addr']" @input="formChanged = true"
                      placeholder="多个联系人请用英文分号';'隔开">
                      <template #suffix>
                        <el-tooltip class="box-item" effect="dark" content="多个联系人请用英文分号';'隔开" placement="top">
                          <IconifyIconOffline :icon="Question" />
                        </el-tooltip>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['cc_addr']" :prop="(['EmailInfo', 'cc_addr'] as any[])">
                    <el-input v-model="emailConfig['EmailInfo']['cc_addr']" @input="formChanged = true"
                      placeholder="多个联系人请用英文分号';'隔开">
                      <template #suffix>
                        <el-tooltip class="box-item" effect="dark" content="多个联系人请用英文分号';'隔开" placement="top">
                          <IconifyIconOffline :icon="Question" />
                        </el-tooltip>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['smtp_server']" :prop="(['EmailInfo', 'smtp_server'] as any[])">
                    <el-input v-model="emailConfig['EmailInfo']['smtp_server']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="emailConfigLabel['subject']" :prop="(['EmailInfo', 'subject'] as any[])">
                    <el-input v-model="emailConfig['EmailInfo']['subject']" @input="formChanged = true">
                    </el-input>
                  </el-form-item>
                </el-card>
              </el-col>
              <!-- <el-col
                :span="12"
                v-for="(obj, section) in emailConfig"
                :key="section"
              >
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>{{ section }}</span>
                    </div>
                  </template>
                  <el-form-item
                    v-for="(value, key) in obj"
                    :label="emailConfigLabel[key] || key"
                    :key="key"
                    :prop="([section, key] as any[])"
                  >
                    <el-input
                      :show-password="(key as any) == 'password'"
                      v-model="emailConfig[section][key]"
                      @input="formChanged = true"
                    >
                      <template
                        v-if="['cc_addr', 'to_addr'].includes(key as any)"
                        #suffix
                      >
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          content="多个联系人请用分号';'隔开"
                          placement="top"
                        >
                          <IconifyIconOffline :icon="Question" />
                        </el-tooltip>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-card>
              </el-col> -->
            </el-row>
            <div class="form-footer">
              <el-button @click="getEmail()">重置</el-button>
              <el-button type="primary" @click="saveEmail()">保存 </el-button>

            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.form-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.demo-tabs {
  margin-top: 20px;
}


.create-item {
  padding-left: 20px;
  margin-bottom: 0;
}

// .project-tabs {
//   height: calc(100vh - 290px);
// }
</style>
